" https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
" Startup {{{
filetype indent plugin on

" }}}

"-----------------------------set vim base-----------------------
"{{{
" Setting some decent VIM settings for programming
set ai                                  " set auto-indenting on for programming
set showmatch                           " automatically show matching brackets. works like it does in bbedit.
set vb                                  " turn on the
set ruler                               " show the cursor position all the time
set laststatus=2                        " make the last line where the status is two lines deep so you can see status always
set backspace=indent,eol,start          " make that backspace key work the way it should
set nocompatible                        " vi compatible is lame
set background=dark                     " use colours that work well on a dark background (console is usually black)
syntax on                               " turn syntax highlighting on by default
set nu                                  " 显示行号
set nobackup                            " 不要备分
set nowb                                " 不备分
set noswapfile                          " 不要交换文件
set mouse=a                             " 鼠标可用
set smartindent                         " 自动缩进
set hlsearch                            " 高亮匹配
set magic                               " 反斜杠有特殊意义
set wildmenu                            " 命令zsh模式
set wildmode=full                       " 命令zsh
set clipboard+=unnamed                  " vim 寄存器与系统剪贴板共享
set fdm=syntax                          " 根据语法折叠
set fdm=expr                            " 手动折叠
set foldmethod=indent                   " 打开缩进折叠
set foldlevel=3                         " 缩进折叠级别
set fileencodings=utf-8,chinese,latin-1 " 设置中文编码
set dy=lastline                         " 显示最多行，不用@@
set sw=4                                " 缩进空格4个
set ts=4                                " 制表符替换成4个空格
set smarttab                            " 缩进首行也是4个空格
syntax on                               " 语法高亮
language messages zh_CN.utf-8           " 解决 CONSLE 输出乱码
au FileType vim setlocal foldmethod=marker "vim 文件折叠方式为 marker

" show eol type and last modified timestamp, right after the filename
set statusline=%<%f%h%m%r\ [%{&ff}]\ (%{strftime(\"%h:%m\ %d/%m/%y\",getftime(expand(\"%:p\")))})%=%l,%c%v\ %p
"}}}



" }}}
"______________________________plug插件_______________________________________
" Plug {{{
"__________________________________________________________________________________
call plug#begin('~/.vim/autoload')
"格式化
Plug 'Chiel92/vim-autoformat'
"增量匹配
Plug 'haya14busa/incsearch.vim'
""git
Plug 'tpope/vim-fugitive'
"状态栏美化
Plug 'itchyny/lightline.vim'
Plug 'vim-airline/vim-airline'
"文件浏览器
Plug 'scrooloose/nerdtree'
""html快速写法
Plug 'mattn/emmet-vim'
"cocvim vscode plc 补全"
Plug 'neoclide/coc.nvim', {'do': { -> coc#util#install()}}
"文件与字搜索"
Plug 'mileszs/ack.vim'
Plug 'kien/ctrlp.vim'
"代码格式化"
Plug 'sbdchd/neoformat'
"扩展语言包"
Plug 'sheerun/vim-polyglot'
"快速注释"
Plug 'tomtom/tcomment_vim'
"中文帮助"
Plug 'yianwillis/vimcdoc'
""主题
Plug 'morhetz/gruvbox'
"处理字符周边符号"
Plug 'tpope/vim-surround'
"对齐文本"
Plug 'godlygeek/tabular'
"vim-go"
Plug 'fatih/vim-go'
"syntastic"
Plug 'scrooloose/syntastic'
" 加强.命令
Plug 'tpope/vim-repeat'
"快速移动"
Plug 'easymotion/vim-easymotion'
"go snips"
""Plug 'SirVer/ultisnips'
call plug#end()

" }}}
"
"
"------------------------------ 键盘映射 --------------------------------
"{{{
"nnoremap <space> @=((foldclosed(line('.')<0)?'zc':'zo'))<CR> "设置键盘映射，通过空格设置折叠
let mapleader=","

map <leader>tn :tabnew<cr>
map <leader>tc :tabclose<cr>
map <leader>th :tabp<cr>
map <leader>tl :tabn<cr>

" 正常模式下 alt+j,k,h,l 调整分割窗口大小
nnoremap <M-j> :resize +5<cr>
nnoremap <M-k> :resize -5<cr>
nnoremap <M-h> :vertical resize -5<cr>
nnoremap <M-l> :vertical resize +5<cr>

""插入模式移动光标 alt + 方向键
inoremap <C-j> <Down>
inoremap <C-k> <Up>
inoremap <C-h> <left>
inoremap <C-l> <Right>

""转换当前行为大写
inoremap <C-u> <esc>

nnoremap <F2> :setlocal number!<cr>
nnoremap <leader>w :set wrap!<cr>

imap <C-v>                 " +gP
vmap <C-c>                 " +y
vnoremap <BS> d
vnoremap <C-C>             " +y
vnoremap <C-Insert>        " +y
imap <C-V>                 " +gP
map <S-Insert>             " +gP
cmap <C-V>      <C-R>+
cmap <S-Insert>     <C-R>+
"}}}



"airline "
"{{{
inoremap <silent> <Bar>   <Bar><Esc>:call <SID>align()<CR>a
function! s:align()
	let p = '^\s*|\s.*\s|\s*$'
	if exists(':Tabularize') && getline('.') =~# '^\s*|' && (getline(line('.')-1) =~# p || getline(line('.')+1) =~# p)
		let column = strlen(substitute(getline('.')[0:col('.')],'[^|]','','g'))
		let position = strlen(matchstr(getline('.')[0:col('.')],'.*|\s*\zs.*'))
		Tabularize/|/l1
		normal! 0
		call search(repeat('[^|]*|',column).'\s\{-\}'.repeat('.',position),'ce',line('.'))
	endif
endfunction
"}}}


" coc 插件相关{{{{

" TextEdit might fail if hidden is not set.
set hidden

" Some servers have issues with backup files, see #649.
set nobackup
set nowritebackup

" Give more space for displaying messages.
set cmdheight=2

" Having longer updatetime (default is 4000 ms = 4 s) leads to noticeable
" delays and poor user experience.
set updatetime=300

" Don't pass messages to |ins-completion-menu|.
set shortmess+=c

" Always show the signcolumn, otherwise it would shift the text each time
" diagnostics appear/become resolved.
if has("patch-8.1.1564")
	" Recently vim can merge signcolumn and number column into one
	set signcolumn=number
else
	set signcolumn=yes
endif

""使用 <tab> 触发补全: >
function! s:check_back_space() abort
	let col = col('.') - 1
	return !col || getline('.')[col - 1]  =~ '\s'
endfunction

inoremap <silent><expr> <TAB>
			\ pumvisible() ? "\<C-n>" :
			\ <SID>check_back_space() ? "\<TAB>" :
			\ coc#refresh()

""使用 <c-space> 强制触发补全: >

inoremap <silent><expr> <c-space> coc#refresh()
""使用 `<cr>` 确认补全： >

inoremap <expr> <cr> pumvisible() ? "\<C-y>" : "\<CR>"
""使用 <CR> 确认补全，并触发 coc.nvim 的 `formatOnType` 功能: >

inoremap <silent><expr> <cr> pumvisible() ? coc#_select_confirm()
			\: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"
"

function! s:check_back_space() abort
	let col = col('.') - 1
	return !col || getline('.')[col - 1]  =~# '\s'
endfunction

" Use <c-space> to trigger completion.
inoremap <silent><expr> <c-space> coc#refresh()

" Use <cr> to confirm completion, `<C-g>u` means break undo chain at current
" position. Coc only does snippet and additional edit on confirm.
" <cr> could be remapped by other vim plugin, try `:verbose imap <CR>`.
if exists('*complete_info')
	inoremap <expr> <cr> complete_info()["selected"] != "-1" ? "\<C-y>" : "\<C-g>u\<CR>"
else
	inoremap <expr> <cr> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
endif

" Use `[g` and `]g` to navigate diagnostics
" Use `:CocDiagnostics` to get all diagnostics of current buffer in location list.
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)

" GoTo code navigation.
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)

" Use K to show documentation in preview window.
nnoremap <silent> K :call <SID>show_documentation()<CR>

function! s:show_documentation()
	if (index(['vim','help'], &filetype) >= 0)
		execute 'h '.expand('<cword>')
	else
		call CocAction('doHover')
	endif
endfunction

" Highlight the symbol and its references when holding the cursor.
autocmd CursorHold * silent call CocActionAsync('highlight')

" Symbol renaming.
nmap <leader>rn <Plug>(coc-rename)

" Formatting selected code.
xmap <leader>f  <Plug>(coc-format-selected)
nmap <leader>f  <Plug>(coc-format-selected)

augroup mygroup
	autocmd!
	" Setup formatexpr specified filetype(s).
	autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected')
	" Update signature help on jump placeholder.
	autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp')
augroup end

" Applying codeAction to the selected region.
" Example: `<leader>aap` for current paragraph
xmap <leader>a  <Plug>(coc-codeaction-selected)
nmap <leader>a  <Plug>(coc-codeaction-selected)

" Remap keys for applying codeAction to the current buffer.
nmap <leader>ac  <Plug>(coc-codeaction)
" Apply AutoFix to problem on the current line.
nmap <leader>qf  <Plug>(coc-fix-current)

" Map function and class text objects
" NOTE: Requires 'textDocument.documentSymbol' support from the language server.
xmap if <Plug>(coc-funcobj-i)
omap if <Plug>(coc-funcobj-i)
xmap af <Plug>(coc-funcobj-a)
omap af <Plug>(coc-funcobj-a)
xmap ic <Plug>(coc-classobj-i)
omap ic <Plug>(coc-classobj-i)
xmap ac <Plug>(coc-classobj-a)
omap ac <Plug>(coc-classobj-a)

" Use CTRL-S for selections ranges.
" Requires 'textDocument/selectionRange' support of LS, ex: coc-tsserver
nmap <silent> <C-s> <Plug>(coc-range-select)
xmap <silent> <C-s> <Plug>(coc-range-select)

" Add `:Format` command to format current buffer.
command! -nargs=0 Format :call CocAction('format')

" Add `:Fold` command to fold current buffer.
command! -nargs=? Fold :call     CocAction('fold', <f-args>)

" Add `:OR` command for organize imports of the current buffer.
command! -nargs=0 OR   :call     CocAction('runCommand', 'editor.action.organizeImport')

" Add (Neo)Vim's native statusline support.
" NOTE: Please see `:h coc-status` for integrations with external plugins that
" provide custom statusline: lightline.vim, vim-airline.
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}

" Mappings for CoCList
" Show all diagnostics.

nnoremap <silent><nowait> <space>g     : <C-u>CocList --normal gstatus<CR>
nnoremap <silent><nowait> <space>a     : <C-u>CocList diagnostics<cr>
" Manage extensions.
nnoremap <silent><nowait> <space>e     : <C-u>CocList extensions<cr>
" Show commands.
nnoremap <silent><nowait> <space>c     : <C-u>CocList commands<cr>
" Find symbol of current document.
nnoremap <silent><nowait> <space>o     : <C-u>CocList outline<cr>
" Search workspace symbols.
nnoremap <silent><nowait> <space>s     : <C-u>CocList -I symbols<cr>
" Do default action for next item.
nnoremap <silent><nowait> <space>j     : <C-u>CocNext<CR>
" Do default action for previous item.
nnoremap <silent><nowait> <space>k     : <C-u>CocPrev<CR>
" Resume latest coc list.
nnoremap <silent><nowait> <space>p     : <C-u>CocListResume<CR>
" }}}}
"


"-------------------------------easymotion ----------------------------
"easymotion{{{
"<Leader>f{char} to move to {char}
map  <Leader>f <Plug>(easymotion-bd-f)
nmap <Leader>f <Plug>(easymotion-overwin-f)

" s{char}{char} to move to {char}{char}
nmap s <Plug>(easymotion-overwin-f2)

" Move to line
map <Leader>L <Plug>(easymotion-bd-jk)
nmap <Leader>L <Plug>(easymotion-overwin-line)

" Move to word
map  <Leader>w <Plug>(easymotion-bd-w)
nmap <Leader>w <Plug>(easymotion-overwin-w)
" }}}

"---------------------------------incsearch----------------------------------
"incsearch{{{
map /  <Plug>(incsearch-forward)
map ?  <Plug>(incsearch-backward)
map g/ <Plug>(incsearch-stay)
" :h g:incsearch#auto_nohlsearch
set hlsearch
let g:incsearch#auto_nohlsearch = 1
map n  <Plug>(incsearch-nohl-n)
map N  <Plug>(incsearch-nohl-N)
map *  <Plug>(incsearch-nohl-*)
map #  <Plug>(incsearch-nohl-#)
map g* <Plug>(incsearch-nohl-g*)
map g# <Plug>(incsearch-nohl-g#)
"}}}

"---------------------------------system----------------------------------------
"{{{

let os=substitute(system('uname'), '\n', '', '')
if os == 'Darwin' || os == 'Mac'
	" more...
	"switch im-select"
	autocmd InsertLeave * call system('im-select com.apple.keylayout.US')
elseif os == 'Linux'
	" more...
endif

if has ("win32")
	let $VIMFILES=$VIM.'/vimfiles'
else
	let $VIMFILES=$HOME.'/.VIM'
endif
set encoding=utf-8
if has("win32")
	set fileencoding=chinese
else
	set fileencoding=utf-8
endif
"}}}

"----------------------------------golang---------------------------------------
"golang site{{{
"map key
"错误跳转
map <C-n> :cnext<CR>
map <C-m> :cprevious<CR>
nnoremap <leader>a :cclose<CR>
let g:go_list_type = "quickfix"
""测试 编译 运行
autocmd FileType go nmap <leader>b <Plug>(go-build)
autocmd FileType go nmap <leader>r <Plug>(go-run)
autocmd FileType go nmap <leader>t <Plug>(go-test)
"测试覆盖率"
autocmd FileType go nmap <Leader>c <Plug>(go-coverage-toggle)
"保存文件优化导入"
let g:go_fmt_command = "goimports"
""函数列表
autocmd Filetype go command! -bang A  call go#alternate#Switch(<bang>0, 'edit')
autocmd Filetype go command! -bang AV call go#alternate#Switch(<bang>0, 'vsplit')
autocmd Filetype go command! -bang AS call go#alternate#Switch(<bang>0, 'split')
autocmd Filetype go command! -bang AT call go#alternate#Switch(<bang>0, 'tabe')
""显示信息
autocmd FileType go nmap <Leader>i <Plug>(go-info)
let g:go_auto_type_info = 1
set updatetime=500
"显示变量信息"
let g:go_auto_sameids = 1
"}}}

"-----------------------------------syntaisic --------------------------------
"{{{
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*

let g:syntastic_always_populate_loc_list = 1
let g:syntastic_auto_loc_list = 1
let g:syntastic_check_on_open = 1
let g:syntastic_check_on_wq = 0
let g:syntastic_javascript_checkers = ['eslint']
let g:syntastic_javascript_eslint_exe = 'npm run lint --'
"}}}
"ag 搜索"
let g:ackprg = 'ag --nogroup --nocolor --column'
let g:ctrlp_working_path_mode = 'ra'
set wildignore+=*/tmp/*,*.so,*.swp,*.zip     " MacOSX/Linux
set wildignore+=*\\tmp\\*,*.swp,*.zip,*.exe  " Windows
set wildignore+=*/node_modules/* 			 " nodejs
let g:ctrlp_custom_ignore = '\v[\/]\.(git|hg|svn)$'
let g:ctrlp_custom_ignore = {
  \ 'dir':  '\v[\/]\.(git|hg|svn)$',
  \ 'file': '\v\.(exe|so|dll)$',
  \ 'link': 'some_bad_symbolic_links',
  \ }

"color
autocmd vimenter * colorscheme gruvbox
"-----------------------------vim-autoformat------------------------------
"{{{
let g:python3_host_prog='/path/to/python/executable/'
noremap <F2> :Autoformat<CR>
"au BufWrite * :Autoformat

"}}}
